
const {ccclass, property} = cc._decorator;

@ccclass
export default class TestPlayerView extends cc.Component {

    @property({
        type: cc.Node,
        displayName: "地图节点"
    })
    map_node: cc.Node = null;
    move_rect: cc.Rect = null;

    @property
    speed: number = 100;

    body: cc.RigidBody = null;

    //当前需要移动的总时间
    move_time: number = 0;
    //x方向速度
    vx: number = 0;
    //y方向速度
    vy: number = 0;
    //是否需要移动
    is_moving: boolean = false;
    //一帧是否移动结束
    is_end: boolean = true;

    onLoad(){
        this.body = this.node.addComponent(cc.RigidBody);
        this.body.type = cc.RigidBodyType.Dynamic;
        let collider = this.node.addComponent(cc.PhysicsBoxCollider);
        collider.offset = cc.v2(this.node.width/2,this.node.height/2);
        collider.size = this.node.getContentSize();
        collider.apply();
    }

    start() {
        this.move_rect = this.map_node.getBoundingBox();
        //this.body = this.node.getComponent(cc.RigidBody);
    }

    moveToTarget(dst: cc.Vec2){
        let src = this.node.getPosition();
        let dir = dst.sub(src);
        let len = dir.mag();
        if(len <= 0){
            return;
        }

        //时间=路程/速度
        this.move_time = len / this.speed;

        //x速度=x长度/时间
        this.vx = dir.x / this.move_time
        //y速度=y长度/时间
        this.vy = dir.y / this.move_time;

        this.body.linearVelocity = cc.v2(this.vx, this.vy);
    }

    update(dt) {

        if(this.move_time <= 0){
            this.body.linearVelocity = cc.v2(0,0);
            return;
        }

        if(this.move_time < dt){
            //最后那一段需要重新计算
            this.vx *= this.move_time / dt;
            this.vy *= this.move_time / dt;
            this.body.linearVelocity = cc.v2(this.vx, this.vy);
        }

        this.move_time -= dt;
    }
}
